package org.exp3;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;

public class Exp3 {
    private JFrame frame;
    private JTextField studentIdField;
    private JTextField courseIdField;
    private JEditorPane resultArea;
    private JLabel instructionLabel;
    private StuDao stuDao = new StuDao();
    private CouDao couDao = new CouDao();
    private ScDao scDao = new ScDao();
    private static final Color PRIMARY_BLUE = new Color(52, 152, 219);
    private static final Color LIGHT_GRAY = new Color(245, 245, 245);
    private static final Font MAIN_FONT = new Font("Microsoft YaHei UI", Font.PLAIN, 14);
    private static final Font BOLD_FONT = new Font("Microsoft YaHei UI", Font.BOLD, 14);
    private static final Font TITLE_FONT = new Font("Microsoft YaHei UI", Font.BOLD, 20);

    public static void main(String[] args) {
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception e) {
            e.printStackTrace();
        }
        SwingUtilities.invokeLater(() -> new Exp3().createAndShowGUI());
    }

    public void createAndShowGUI() {
        frame = new JFrame("数据实验3——MySQL基本查询");
        frame.setSize(1000, 800);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        JPanel mainPanel = new JPanel();
        mainPanel.setLayout(new BorderLayout());
        mainPanel.setBorder(new EmptyBorder(20, 20, 20, 20));
        mainPanel.setBackground(LIGHT_GRAY);
        JPanel topPanel = new JPanel();
        topPanel.setLayout(new BorderLayout(20, 10));
        topPanel.setOpaque(false);
        JPanel inputPanel = new JPanel();
        inputPanel.setLayout(new GridBagLayout());
        inputPanel.setOpaque(false);
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(8, 10, 8, 10);
        JLabel studentIdLabel = new JLabel("学生 ID(0为所有)");
        studentIdLabel.setFont(BOLD_FONT);
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.anchor = GridBagConstraints.EAST;
        inputPanel.add(studentIdLabel, gbc);
        studentIdField = createStyledTextField("0");
        studentIdField.setPreferredSize(new Dimension(180, 35));
        gbc.gridx = 1;
        gbc.gridy = 0;
        gbc.anchor = GridBagConstraints.WEST;
        inputPanel.add(studentIdField, gbc);
        JLabel courseIdLabel = new JLabel("课程 ID(0为所有)");
        courseIdLabel.setFont(BOLD_FONT);
        gbc.gridx = 0;
        gbc.gridy = 1;
        gbc.anchor = GridBagConstraints.EAST;
        inputPanel.add(courseIdLabel, gbc);
        courseIdField = createStyledTextField("0");
        courseIdField.setPreferredSize(new Dimension(180, 35));
        gbc.gridx = 1;
        gbc.gridy = 1;
        gbc.anchor = GridBagConstraints.WEST;
        inputPanel.add(courseIdField, gbc);
        JPanel buttonPanel = new JPanel();
        buttonPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 20, 10));
        buttonPanel.setOpaque(false);

        JButton addButton = createStyledButton("增", new Color(46, 204, 113));
        JButton deleteButton = createStyledButton("删", new Color(231, 76, 60));
        JButton updateButton = createStyledButton("改", new Color(243, 156, 18));
        JButton queryButton = createStyledButton("查", PRIMARY_BLUE);

        buttonPanel.add(addButton);
        buttonPanel.add(deleteButton);
        buttonPanel.add(updateButton);
        buttonPanel.add(queryButton);

        JPanel instructionPanel = new JPanel(new BorderLayout());
        instructionPanel.setOpaque(false);
        instructionPanel.setBorder(BorderFactory.createTitledBorder(
                BorderFactory.createLineBorder(PRIMARY_BLUE), "使用说明",
                javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION,
                javax.swing.border.TitledBorder.DEFAULT_POSITION,
                BOLD_FONT, PRIMARY_BLUE));
        JScrollPane instructionScrollPane = new JScrollPane(instructionPanel);
        instructionScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
        instructionScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        instructionScrollPane.setBorder(null); // 移除默认边框
        topPanel.add(instructionScrollPane, BorderLayout.EAST);
        instructionLabel = new JLabel(
                "<html>" +
                        "<b>【查询操作 '查'】</b><br>" +
                        "• S ID=0, C ID=0: 查询所有学生和课程信息。<br>" +
                        "• S ID!=0, C ID=0: 查询该学生详细信息。<br>" +
                        "• S ID=0, C ID!=0: 查询该课程详细信息。<br>" +
                        "• S ID!=0, C ID!=0: 查询该选课记录成绩。<br>" +
                        "<hr style='margin: 3px 0; border-color:#ccc;'>" +
                        "<b>【增/删/改操作】</b><br>" +
                        "&nbsp; - <b>增:</b> 输入ID确定对象后，点击'增'，弹出对话框填写新信息。<br>" +
                        "&nbsp; - <b>改:</b> 输入ID定位记录后，点击'改'，预填原值后修改。<br>" +
                        "&nbsp; - <b>删:</b> 输入ID定位记录后，点击'删'，直接删除。<br>" +
                        "&nbsp;&nbsp;&nbsp;&nbsp;• S ID!=0, C ID=0: 目标为 <b>学生</b>。<br>" +
                        "&nbsp;&nbsp;&nbsp;&nbsp;• S ID=0, C ID!=0: 目标为 <b>课程</b>。<br>" +
                        "&nbsp;&nbsp;&nbsp;&nbsp;• S ID!=0, C ID!=0: 目标为 <b>选课记录</b>。" +
                        "</html>"
        );
        instructionLabel.setVerticalAlignment(SwingConstants.TOP);
        instructionLabel.setFont(MAIN_FONT);
        instructionLabel.setBorder(new EmptyBorder(5, 5, 5, 5));
        instructionPanel.add(instructionLabel, BorderLayout.CENTER);
        JPanel inputAndButtonWrapper = new JPanel(new BorderLayout());
        inputAndButtonWrapper.setOpaque(false);
        inputAndButtonWrapper.add(inputPanel, BorderLayout.NORTH);
        inputAndButtonWrapper.add(buttonPanel, BorderLayout.CENTER);
        topPanel.add(inputAndButtonWrapper, BorderLayout.CENTER);
        topPanel.add(instructionPanel, BorderLayout.EAST);
        resultArea = new JEditorPane();
        resultArea.setEditable(false);
        resultArea.setContentType("text/html");
        resultArea.setFont(MAIN_FONT);
        resultArea.setBackground(Color.WHITE);
        resultArea.setBorder(BorderFactory.createTitledBorder(
                BorderFactory.createLineBorder(PRIMARY_BLUE), "查询结果",
                javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION,
                javax.swing.border.TitledBorder.DEFAULT_POSITION,
                TITLE_FONT, PRIMARY_BLUE));
        JScrollPane scrollPane = new JScrollPane(resultArea);
        scrollPane.setBorder(null);
        mainPanel.add(topPanel, BorderLayout.NORTH);
        mainPanel.add(scrollPane, BorderLayout.CENTER);
        setupActionListeners(addButton, deleteButton, updateButton, queryButton);
        frame.add(mainPanel);
        frame.setVisible(true);
    }

    private JButton createStyledButton(String text, Color color) {
        JButton button = new JButton(text);
        button.setPreferredSize(new Dimension(80, 40));
        button.setFont(BOLD_FONT.deriveFont(16f));
        button.setBackground(color);
        button.setForeground(Color.BLACK);
        button.setFocusPainted(false);
        button.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(color.darker(), 2),
                BorderFactory.createEmptyBorder(8, 15, 8, 15)));
        button.setMargin(new Insets(0, 0, 0, 0));
        button.putClientProperty("JButton.rounded", true);
        return button;
    }

    private JTextField createStyledTextField(String text) {
        JTextField field = new JTextField(text);
        field.setPreferredSize(new Dimension(150, 30));
        field.setFont(MAIN_FONT);
        field.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(Color.LIGHT_GRAY),
                BorderFactory.createEmptyBorder(5, 5, 5, 5)));
        return field;
    }

    private JPanel createStyledPanel(int rows) {
        JPanel panel = new JPanel(new GridLayout(rows, 2, 10, 10));
        panel.setBorder(new EmptyBorder(10, 10, 10, 10));
        panel.setOpaque(false);
        return panel;
    }

    private JLabel createStyledLabel(String text) {
        JLabel label = new JLabel(text, SwingConstants.RIGHT);
        label.setFont(BOLD_FONT);
        return label;
    }

    private String toHtmlColor(Color color) {
        return String.format("#%02x%02x%02x", color.getRed(), color.getGreen(), color.getBlue());
    }

    private void setupActionListeners(JButton addButton, JButton deleteButton,
                                      JButton updateButton, JButton queryButton) {
        // 查询按钮点击事件
        queryButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    int studentId = Integer.parseInt(studentIdField.getText());
                    int courseId = Integer.parseInt(courseIdField.getText());

                    if (studentId == 0 && courseId == 0) {
                        handleQueryAllInfo();
                    } else if (studentId == 0) {
                        handleQueryCourseDetail(courseId);
                    } else if (courseId == 0) {
                        handleQueryStudentDetail(studentId);
                    } else {
                        handleQuerySpecificSC(studentId, courseId);
                    }
                } catch (NumberFormatException ex) {
                    displayHtmlResult(wrapInHtmlBody("<p style='color:red;'>请输入有效的数字</p>"));
                }
            }
        });

        // 增加按钮点击事件 - 新增路由逻辑
        addButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                handleAddActionRouter();
            }
        });

        // 删除按钮点击事件
        deleteButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                deleteActionRouter();
            }
        });

        // 修改按钮点击事件
        updateButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                updateActionRouter();
            }
        });
    }

    private void displayHtmlResult(String htmlContent) {
        resultArea.setContentType("text/html");
        resultArea.setText(htmlContent);
    }

    private String wrapInHtmlBody(String content) {
        return "<html><body style='font-family:Microsoft YaHei UI; font-size:14px;'>"
                + content
                + "</body></html>";
    }

    // --- 查询操作 (Query Handlers) ---
    private void handleQueryAllInfo() {
        StringBuilder sb = new StringBuilder();
        sb.append(generateStudentTable(stuDao.getAllStudents()));
        sb.append("<br><hr style='border-color: #ccc;'><br>");
        sb.append(generateCourseTable(couDao.getAllCourese()));

        String html = wrapInHtmlBody(sb.toString());
        displayHtmlResult(html);
    }

    private void handleQueryCourseDetail(int courseId) {
        Course course = couDao.getCoureseById(courseId);
        StringBuilder sb = new StringBuilder();
        sb.append("<h4 style='color:").append(toHtmlColor(PRIMARY_BLUE)).append(";'>课程信息</h4>");
        sb.append(generateCourseDetailHtml(course));

        String html = wrapInHtmlBody(sb.toString());
        displayHtmlResult(html);
    }

    private void handleQueryStudentDetail(int studentId) {
        Student stu = stuDao.getStudentById(studentId);
        StringBuilder sb = new StringBuilder();
        sb.append("<h3>查询结果</h3>");
        if (stu != null) {
            sb.append("<h4 style='color:").append(toHtmlColor(PRIMARY_BLUE)).append(";'>学生信息</h4>");
            sb.append(generateStudentDetailHtml(stu));
        } else {
            sb.append("<p style='color:red;'>未找到该学生</p>");
        }

        String html = wrapInHtmlBody(sb.toString());
        displayHtmlResult(html);
    }

    private void handleQuerySpecificSC(int studentId, int courseId) {
        SC sc = scDao.getSCByStudentIdAndCourseId(studentId, courseId);
        if (sc != null) {
            course_t courseT = new course_t();
            courseT.setStuid(sc.getStuid());
            courseT.setCouid(sc.getCouid());
            courseT.setGrade(sc.getGrade());
            displayResult(List.of(courseT));
        } else {
            displayHtmlResult(wrapInHtmlBody("<p style='color:red;'>未找到匹配的选课记录 (学生ID: " + studentId + ", 课程ID: " + courseId + ")</p>"));
        }
    }

    private void handleAddActionRouter() {
        try {
            int studentId = Integer.parseInt(studentIdField.getText());
            int courseId = Integer.parseInt(courseIdField.getText());

            if (studentId == 0 && courseId == 0) {
                JOptionPane.showMessageDialog(frame, "请输入学生ID或课程ID来确定新增类型！", "输入错误", JOptionPane.ERROR_MESSAGE);
            } else if (studentId == 0 && courseId != 0) {
                showAddCourseDialog();
            } else if (studentId != 0 && courseId == 0) {
                showAddStudentDialog();
            } else {
                showAddSCDialog(studentId, courseId);
            }
        } catch (NumberFormatException ex) {
            JOptionPane.showMessageDialog(frame, "请输入有效的数字", "输入错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void showAddSCDialog(int studentId, int courseId) {
        JDialog dialog = new JDialog(frame, "新增选课记录", true);
        dialog.setSize(400, 250);
        dialog.setLocationRelativeTo(frame);

        JPanel panel = createStyledPanel(3);

        panel.add(createStyledLabel("学生ID:"));
        panel.add(new JLabel(String.valueOf(studentId), SwingConstants.LEFT));

        panel.add(createStyledLabel("课程ID:"));
        panel.add(new JLabel(String.valueOf(courseId), SwingConstants.LEFT));

        JLabel gradeLabel = createStyledLabel("成绩:");
        JTextField gradeField = createStyledTextField("");
        panel.add(gradeLabel);
        panel.add(gradeField);

        JButton confirmButton = createStyledButton("确认", new Color(46, 204, 113));
        JButton cancelButton = createStyledButton("取消", Color.GRAY);
        confirmButton.addActionListener(e -> {
            try {
                float grade = Float.parseFloat(gradeField.getText());
                SC sc = new SC(studentId, courseId, grade);
                System.out.println("控制台日志: 尝试新增选课记录 (学生ID: " + studentId + ", 课程ID: " + courseId + ", 成绩: " + grade + ")");
                scDao.addSC(sc);
                displayHtmlResult(wrapInHtmlBody("<p style='color:green;'>新增选课记录成功！学生ID: " + studentId + ", 课程ID: " + courseId + "</p>"));
                System.out.println("控制台日志: 新增选课记录操作成功。");
                dialog.dispose();
            } catch (NumberFormatException ex) {
                JOptionPane.showMessageDialog(dialog, "成绩输入格式错误", "输入错误", JOptionPane.ERROR_MESSAGE);
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(dialog, "新增选课记录失败！请检查ID和成绩。详情请看控制台。", "操作失败", JOptionPane.ERROR_MESSAGE);
                System.err.println("控制台日志: 新增选课记录操作失败。");
                displayHtmlResult(wrapInHtmlBody("<p style='color:red;'>新增选课记录失败！请检查ID是否已存在或有效。</p>"));
            }
        });

        cancelButton.addActionListener(e -> dialog.dispose());

        JPanel buttonRow = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 0));
        buttonRow.setOpaque(false);
        buttonRow.add(confirmButton);
        buttonRow.add(cancelButton);

        dialog.setLayout(new BorderLayout(10, 10));
        dialog.add(panel, BorderLayout.CENTER);
        dialog.add(buttonRow, BorderLayout.SOUTH);
        dialog.setVisible(true);
    }

    private void showAddStudentDialog() {
        JDialog dialog = new JDialog(frame, "新增学生信息", true);
        dialog.setSize(400, 400);
        dialog.setLocationRelativeTo(frame);

        JPanel panel = createStyledPanel(6);

        JTextField studentIdField = createStyledTextField("");
        JTextField nameField = createStyledTextField("");
        JTextField genderField = createStyledTextField("");
        JTextField yearField = createStyledTextField("");
        JTextField phoneField = createStyledTextField("");
        JTextField majorField = createStyledTextField("");

        panel.add(createStyledLabel("学生ID:"));
        panel.add(studentIdField);
        panel.add(createStyledLabel("姓名:"));
        panel.add(nameField);
        panel.add(createStyledLabel("性别(M/F):"));
        panel.add(genderField);
        panel.add(createStyledLabel("入学年份:"));
        panel.add(yearField);
        panel.add(createStyledLabel("电话(可空):"));
        panel.add(phoneField);
        panel.add(createStyledLabel("专业:"));
        panel.add(majorField);

        JButton confirmButton = createStyledButton("确认", new Color(46, 204, 113));
        JButton cancelButton = createStyledButton("取消", Color.GRAY);
        confirmButton.addActionListener(e -> {
            try {
                int studentId = Integer.parseInt(studentIdField.getText());
                String name = nameField.getText();
                String gender = genderField.getText();
                String year = yearField.getText();
                String phone = phoneField.getText().trim().isEmpty() ? null : phoneField.getText();
                String major = majorField.getText();

                Student stu = new Student(studentId, name, gender, year, phone, major);
                System.out.println("控制台日志: 尝试新增学生 (ID: " + studentId + ", 姓名: " + name + ")");
                stuDao.addStudent(stu);
                displayHtmlResult(wrapInHtmlBody("<p style='color:green;'>新增学生成功！ID: " + studentId + ", 姓名: " + name + "</p>"));
                System.out.println("控制台日志: 新增学生操作成功。");
                dialog.dispose();
            } catch (NumberFormatException ex) {
                JOptionPane.showMessageDialog(dialog, "学生ID或年份输入格式错误", "输入错误", JOptionPane.ERROR_MESSAGE);
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(dialog, "新增学生信息失败！请检查ID和必填信息。详情请看控制台。", "操作失败", JOptionPane.ERROR_MESSAGE);
                System.err.println("控制台日志: 新增学生操作失败。");
                // 修复：使
                displayHtmlResult(wrapInHtmlBody("<p style='color:red;'>新增学生信息失败！请检查ID是否已存在或有效。</p>"));
            }
        });

        cancelButton.addActionListener(e -> dialog.dispose());

        JPanel buttonRow = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 10));
        buttonRow.setOpaque(false);
        buttonRow.add(confirmButton);
        buttonRow.add(cancelButton);

        dialog.setLayout(new BorderLayout(10, 10));
        dialog.add(panel, BorderLayout.CENTER);
        dialog.add(buttonRow, BorderLayout.SOUTH);
        dialog.setVisible(true);
    }

    private void showAddCourseDialog() {
        JDialog dialog = new JDialog(frame, "新增课程信息", true);
        dialog.setSize(400, 400);
        dialog.setLocationRelativeTo(frame);

        JPanel panel = createStyledPanel(6);

        JTextField courseIdField = createStyledTextField("");
        JTextField nameField = createStyledTextField("");
        JTextField creditsField = createStyledTextField("");
        JTextField hoursField = createStyledTextField("");
        JTextField semesterField = createStyledTextField("");
        JTextField couPnoField = createStyledTextField("");

        panel.add(createStyledLabel("课程ID:"));
        panel.add(courseIdField);
        panel.add(createStyledLabel("课程名称:"));
        panel.add(nameField);
        panel.add(createStyledLabel("学分:"));
        panel.add(creditsField);
        panel.add(createStyledLabel("学时:"));
        panel.add(hoursField);
        panel.add(createStyledLabel("学期:"));
        panel.add(semesterField);
        panel.add(createStyledLabel("先修课程ID(可空):"));
        panel.add(couPnoField);


        JButton confirmButton = createStyledButton("确认", new Color(46, 204, 113));
        JButton cancelButton = createStyledButton("取消", Color.GRAY);
        confirmButton.addActionListener(e -> {
            try {
                int courseId = Integer.parseInt(courseIdField.getText());
                String name = nameField.getText();
                float credits = Float.parseFloat(creditsField.getText());
                String hours = hoursField.getText();
                String semester = semesterField.getText();

                int couPno;
                String couPnoText = couPnoField.getText().trim();
                if (couPnoText.isEmpty()) {
                    couPno = 0;
                } else {
                    couPno = Integer.parseInt(couPnoText);
                }

                Course cou = new Course(courseId, name, credits, hours, semester, couPno);
                System.out.println("控制台日志: 尝试新增课程 (ID: " + courseId + ", 名称: " + name + ", 先修ID: " + couPno + ")");
                couDao.addCourese(cou);
                displayHtmlResult(wrapInHtmlBody("<p style='color:green;'>新增课程成功！ID: " + courseId + ", 名称: " + name + "</p>"));
                System.out.println("控制台日志: 新增课程操作成功。");
                dialog.dispose();
            } catch (NumberFormatException ex) {
                JOptionPane.showMessageDialog(dialog, "ID、学时、学分或先修课程ID输入格式错误", "输入错误", JOptionPane.ERROR_MESSAGE);
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(dialog, "新增课程信息失败！请检查ID和必填信息。详情请看控制台。", "操作失败", JOptionPane.ERROR_MESSAGE);
                System.err.println("控制台日志: 新增课程操作失败。");
                // 修复：使
                displayHtmlResult(wrapInHtmlBody("<p style='color:red;'>新增课程信息失败！请检查ID是否已存在或有效。</p>"));
            }
        });

        cancelButton.addActionListener(e -> dialog.dispose());

        JPanel buttonRow = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 10));
        buttonRow.setOpaque(false);
        buttonRow.add(confirmButton);
        buttonRow.add(cancelButton);

        dialog.setLayout(new BorderLayout(10, 10));
        dialog.add(panel, BorderLayout.CENTER);
        dialog.add(buttonRow, BorderLayout.SOUTH);
        dialog.setVisible(true);
    }

    // --- 删除操作路由 (Delete Handler) ---
    private void deleteActionRouter() {
        try {
            int studentId = Integer.parseInt(studentIdField.getText());
            int courseId = Integer.parseInt(courseIdField.getText());
            boolean success = false;
            String resultMessage;

            if (studentId == 0 && courseId == 0) {
                JOptionPane.showMessageDialog(frame, "请至少输入学生ID或课程ID来确定删除目标！", "输入错误", JOptionPane.ERROR_MESSAGE);
                return;
            } else if (studentId != 0 && courseId == 0) {
                // 删除学生
                System.out.println("控制台日志: 尝试删除学生 (ID: " + studentId + ")");
                success = stuDao.deleteStudent(studentId);
                resultMessage = success ? "删除学生成功！ID: " + studentId : "删除学生失败，未找到该学生！ID: " + studentId;
            } else if (studentId == 0 && courseId != 0) {
                // 删除课程
                System.out.println("控制台日志: 尝试删除课程 (ID: " + courseId + ")");
                success = couDao.deleteCourese(courseId);
                resultMessage = success ? "删除课程成功！ID: " + courseId : "删除课程失败，未找到该课程！ID: " + courseId;
            } else {
                // 删除选课记录 (SC)
                System.out.println("控制台日志: 尝试删除选课记录 (学生ID: " + studentId + ", 课程ID: " + courseId + ")");
                success = scDao.deleteSC(studentId, courseId);
                resultMessage = success ? "删除选课记录成功！学生ID: " + studentId + ", 课程ID: " + courseId : "删除选课记录失败，未找到匹配记录！";
            }
            String color = success ? "green" : "red";
            String htmlMessage = "<p style='color:" + color + ";'>" + resultMessage + "</p>";
            displayHtmlResult(wrapInHtmlBody(htmlMessage));
            System.out.println("控制台日志: 操作结果 - " + resultMessage);

        } catch (NumberFormatException ex) {
            displayHtmlResult(wrapInHtmlBody("<p style='color:red;'>请输入有效的数字</p>"));
            JOptionPane.showMessageDialog(frame, "请输入有效的数字", "输入错误", JOptionPane.ERROR_MESSAGE);
        } catch (Exception ex) {
            displayHtmlResult(wrapInHtmlBody("<p style='color:red;'>删除操作失败: " + ex.getMessage() + "</p>"));
            System.err.println("控制台日志: 删除操作发生异常！");
            ex.printStackTrace();
        }
    }


    // --- 修改操作路由及对话框 (Update Handlers) ---
    private void updateActionRouter() {
        try {
            int studentId = Integer.parseInt(studentIdField.getText());
            int courseId = Integer.parseInt(courseIdField.getText());

            if (studentId == 0 && courseId == 0) {
                JOptionPane.showMessageDialog(frame, "请输入学生ID或课程ID来确定修改类型！", "输入错误", JOptionPane.ERROR_MESSAGE);
            } else if (studentId != 0 && courseId == 0) {
                showUpdateStudentDialog(studentId);
            } else if (studentId == 0 && courseId != 0) {
                showUpdateCourseDialog(courseId);
            } else {
                showUpdateSCDialog(studentId, courseId);
            }
        } catch (NumberFormatException ex) {
            JOptionPane.showMessageDialog(frame, "请输入有效的数字", "输入错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    // 修改选课成绩对话框
    private void showUpdateSCDialog(int studentId, int courseId) {
        SC existingSC = scDao.getSCByStudentIdAndCourseId(studentId, courseId);
        if (existingSC == null) {
            JOptionPane.showMessageDialog(frame, "未找到该学生-课程的选课记录！", "查询失败", JOptionPane.WARNING_MESSAGE);
            return;
        }

        JDialog dialog = new JDialog(frame, "修改选课成绩", true);
        dialog.setSize(350, 200);
        dialog.setLocationRelativeTo(frame);

        JPanel panel = createStyledPanel(3);

        panel.add(createStyledLabel("学生ID:"));
        panel.add(new JLabel(String.valueOf(studentId)));

        panel.add(createStyledLabel("课程ID:"));
        panel.add(new JLabel(String.valueOf(courseId)));

        JLabel gradeLabel = createStyledLabel("新成绩:");
        JTextField gradeField = createStyledTextField(String.valueOf(existingSC.getGrade())); // 预填原成绩
        panel.add(gradeLabel);
        panel.add(gradeField);

        JButton confirmButton = createStyledButton("确认修改", new Color(243, 156, 18));
        JButton cancelButton = createStyledButton("取消", Color.GRAY);

        confirmButton.addActionListener(e -> {
            try {
                float grade = Float.parseFloat(gradeField.getText());

                SC sc = new SC(studentId, courseId, grade);
                System.out.println("控制台日志: 尝试修改选课记录 (学生ID: " + studentId + ", 课程ID: " + courseId + ", 新成绩: " + grade + ")");
                boolean success = scDao.updateSC(sc);
                if (success) {
                    displayHtmlResult(wrapInHtmlBody("<p style='color:green;'>修改成绩成功！</p>"));
                } else {
                    displayHtmlResult(wrapInHtmlBody("<p style='color:red;'>修改成绩失败，未找到匹配记录</p>"));
                }
                System.out.println("控制台日志: 修改选课记录操作完成，结果: " + (success ? "成功" : "失败"));
                dialog.dispose();
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(dialog, "输入格式错误，请检查数据");
                System.err.println("控制台日志: 修改选课记录操作失败。");
            }
        });

        cancelButton.addActionListener(e -> dialog.dispose());

        JPanel buttonRow = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 10));
        buttonRow.setOpaque(false);
        buttonRow.add(confirmButton);
        buttonRow.add(cancelButton);

        dialog.setLayout(new BorderLayout(10, 10));
        dialog.add(panel, BorderLayout.CENTER);
        dialog.add(buttonRow, BorderLayout.SOUTH);
        dialog.setVisible(true);
    }

    // 修改学生信息对话框
    private void showUpdateStudentDialog(int studentId) {
        Student stu = stuDao.getStudentById(studentId);
        if (stu == null) {
            JOptionPane.showMessageDialog(frame, "未找到学生ID: " + studentId + " 的记录！", "查询失败", JOptionPane.WARNING_MESSAGE);
            return;
        }
        JDialog dialog = new JDialog(frame, "修改学生信息", true);
        dialog.setSize(400, 400);
        dialog.setLocationRelativeTo(frame);
        JPanel panel = createStyledPanel(6);
        JTextField studentIdField = createStyledTextField(String.valueOf(stu.getStuid()));
        studentIdField.setEditable(false);
        studentIdField.setBackground(LIGHT_GRAY.brighter());
        JTextField nameField = createStyledTextField(stu.getStuName());
        JTextField genderField = createStyledTextField(stu.getStuGender());
        JTextField yearField = createStyledTextField(stu.getEnrolledYear());
        JTextField phoneField = createStyledTextField(stu.getStuPhone() != null ? stu.getStuPhone() : "");
        JTextField majorField = createStyledTextField(stu.getStuMajor());

        panel.add(createStyledLabel("学生ID(不可改):"));
        panel.add(studentIdField);
        panel.add(createStyledLabel("姓名:"));
        panel.add(nameField);
        panel.add(createStyledLabel("性别(M/F):"));
        panel.add(genderField);
        panel.add(createStyledLabel("入学年份:"));
        panel.add(yearField);
        panel.add(createStyledLabel("电话(可空):"));
        panel.add(phoneField);
        panel.add(createStyledLabel("专业:"));
        panel.add(majorField);

        JButton confirmButton = createStyledButton("确认修改", new Color(243, 156, 18));
        JButton cancelButton = createStyledButton("取消", Color.GRAY);

        confirmButton.addActionListener(e -> {
            try {
                String name = nameField.getText();
                String gender = genderField.getText();
                String year = yearField.getText();
                String phone = phoneField.getText().trim().isEmpty() ? null : phoneField.getText();
                String major = majorField.getText();

                Student updatedStu = new Student(studentId, name, gender, year, phone, major);
                System.out.println("控制台日志: 尝试修改学生信息 (ID: " + studentId + ")");
                boolean success = stuDao.updateStudent(updatedStu);
                if (success) {
                    displayHtmlResult(wrapInHtmlBody("<p style='color:green;'>修改学生信息成功！ID: " + studentId + "</p>"));
                } else {
                    displayHtmlResult(wrapInHtmlBody("<p style='color:red;'>修改学生信息失败！</p>"));
                }
                System.out.println("控制台日志: 修改学生信息操作完成，结果: " + (success ? "成功" : "失败"));
                dialog.dispose();
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(dialog, "修改学生信息失败！请检查数据格式。", "操作失败", JOptionPane.ERROR_MESSAGE);
                System.err.println("控制台日志: 修改学生信息操作失败。");
            }
        });

        cancelButton.addActionListener(e -> dialog.dispose());

        JPanel buttonRow = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 10));
        buttonRow.setOpaque(false);
        buttonRow.add(confirmButton);
        buttonRow.add(cancelButton);

        dialog.setLayout(new BorderLayout(10, 10));
        dialog.add(panel, BorderLayout.CENTER);
        dialog.add(buttonRow, BorderLayout.SOUTH);
        dialog.setVisible(true);
    }

    // 修改课程信息对话框
    private void showUpdateCourseDialog(int courseId) {
        Course cou = couDao.getCoureseById(courseId);
        if (cou == null) {
            JOptionPane.showMessageDialog(frame, "未找到课程ID: " + courseId + " 的记录！", "查询失败", JOptionPane.WARNING_MESSAGE);
            return;
        }

        JDialog dialog = new JDialog(frame, "修改课程信息", true);
        dialog.setSize(400, 400);
        dialog.setLocationRelativeTo(frame);

        JPanel panel = createStyledPanel(6);

        // 预填现有数据
        JTextField courseIdField = createStyledTextField(String.valueOf(cou.getCouid()));
        courseIdField.setEditable(false);
        courseIdField.setBackground(LIGHT_GRAY.brighter());
        JTextField nameField = createStyledTextField(cou.getCoursename());
        JTextField creditsField = createStyledTextField(String.valueOf(cou.getCredits()));
        JTextField hoursField = createStyledTextField(cou.getHours());
        JTextField semesterField = createStyledTextField(cou.getSemester());
        // 如果 CouPno 是 0 (表示 NULL)，显示为空字符串，否则显示实际值
        String couPnoText = (cou.getCouPno() != 0) ? String.valueOf(cou.getCouPno()) : "";
        JTextField couPnoField = createStyledTextField(couPnoText);
        panel.add(createStyledLabel("课程ID(不可改):"));
        panel.add(courseIdField);
        panel.add(createStyledLabel("课程名称:"));
        panel.add(nameField);
        panel.add(createStyledLabel("学分:"));
        panel.add(creditsField);
        panel.add(createStyledLabel("学时:"));
        panel.add(hoursField);
        panel.add(createStyledLabel("学期:"));
        panel.add(semesterField);
        panel.add(createStyledLabel("先修课程ID(可空):"));
        panel.add(couPnoField);
        JButton confirmButton = createStyledButton("确认修改", new Color(243, 156, 18));
        JButton cancelButton = createStyledButton("取消", Color.GRAY);
        confirmButton.addActionListener(e -> {
            try {
                // 获取新值 (未修改的字段会保持原值)
                String name = nameField.getText();
                float credits = Float.parseFloat(creditsField.getText());
                String hours = hoursField.getText();
                String semester = semesterField.getText();

                int couPno;
                String newCouPnoText = couPnoField.getText().trim();
                if (newCouPnoText.isEmpty()) {
                    couPno = 0;
                } else {
                    couPno = Integer.parseInt(newCouPnoText);
                }

                Course updatedCou = new Course(courseId, name, credits, hours, semester, couPno);
                System.out.println("控制台日志: 尝试修改课程信息 (ID: " + courseId + ", 新先修ID: " + couPno + ")");
                boolean success = couDao.updateCourese(updatedCou);

                if (success) {
                    displayHtmlResult(wrapInHtmlBody("<p style='color:green;'>修改课程信息成功！ID: " + courseId + ", 名称: " + name + "</p>"));
                } else {
                    displayHtmlResult(wrapInHtmlBody("<p style='color:red;'>修改课程信息失败！</p>"));
                }
                System.out.println("控制台日志: 修改课程信息操作完成，结果: " + (success ? "成功" : "失败"));
                dialog.dispose();
            } catch (NumberFormatException ex) {
                JOptionPane.showMessageDialog(dialog, "学分、学时或先修课程ID输入格式错误", "输入错误", JOptionPane.ERROR_MESSAGE);
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(dialog, "修改课程信息失败！请检查必填信息。", "操作失败", JOptionPane.ERROR_MESSAGE);
                System.err.println("控制台日志: 修改课程信息操作失败。");
            }
        });

        cancelButton.addActionListener(e -> dialog.dispose());

        JPanel buttonRow = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 10));
        buttonRow.setOpaque(false);
        buttonRow.add(confirmButton);
        buttonRow.add(cancelButton);

        dialog.setLayout(new BorderLayout(10, 10));
        dialog.add(panel, BorderLayout.CENTER);
        dialog.add(buttonRow, BorderLayout.SOUTH);
        dialog.setVisible(true);
    }

    private String generateStudentTable(List<Student> studentList) {
        StringBuilder sb = new StringBuilder();
        sb.append("<h3 style='color:").append(toHtmlColor(PRIMARY_BLUE)).append(";'>所有学生信息</h3>");
        if (studentList.isEmpty()) {
            sb.append("<p>暂无学生数据</p>");
        } else {
            String tableStyle = "width: 100%; border-collapse: collapse; font-family: Microsoft YaHei UI;";
            String thStyle = "border: 1px solid #ddd; padding: 10px; text-align: left; background-color: #f0f8ff; color: #333;";
            String tdStyle = "border: 1px solid #ddd; padding: 10px; text-align: left;";
            sb.append("<table style='").append(tableStyle).append("'>");
            sb.append("<tr>");
            sb.append("<th style='").append(thStyle).append("'>学生ID</th>");
            sb.append("<th style='").append(thStyle).append("'>姓名</th>");
            sb.append("<th style='").append(thStyle).append("'>性别</th>");
            sb.append("<th style='").append(thStyle).append("'>入学年份</th>");
            sb.append("<th style='").append(thStyle).append("'>电话</th>");
            sb.append("<th style='").append(thStyle).append("'>专业</th>");
            sb.append("</tr>");
            for (int i = 0; i < studentList.size(); i++) {
                Student stu = studentList.get(i);
                sb.append("<tr>")
                        .append("<td style='").append(tdStyle).append("'>").append(stu.getStuid()).append("</td>")
                        .append("<td style='").append(tdStyle).append("'>").append(stu.getStuName()).append("</td>")
                        .append("<td style='").append(tdStyle).append("'>").append(stu.getStuGender()).append("</td>")
                        .append("<td style='").append(tdStyle).append("'>").append(stu.getEnrolledYear()).append("</td>")
                        .append("<td style='").append(tdStyle).append("'>").append(stu.getStuPhone() != null ? stu.getStuPhone() : "未填写").append("</td>")
                        .append("<td style='").append(tdStyle).append("'>").append(stu.getStuMajor()).append("</td>")
                        .append("</tr>");
            }
            sb.append("</table>");
        }
        return sb.toString();
    }

    private String generateCourseTable(List<Course> courseList) {
        StringBuilder sb = new StringBuilder();
        sb.append("<h3 style='color:").append(toHtmlColor(PRIMARY_BLUE)).append(";'>所有课程信息</h3>");
        if (courseList.isEmpty()) {
            sb.append("<p>暂无课程数据</p>");
        } else {
            String tableStyle = "width: 100%; border-collapse: collapse; font-family: Microsoft YaHei UI;";
            String thStyle = "border: 1px solid #ddd; padding: 10px; text-align: left; background-color: #f0f8ff; color: #333;";
            String tdStyle = "border: 1px solid #ddd; padding: 10px; text-align: left;";

            sb.append("<table style='").append(tableStyle).append("'>")
                    .append("<tr>");
            sb.append("<th style='").append(thStyle).append("'>课程ID</th>");
            sb.append("<th style='").append(thStyle).append("'>课程名称</th>");
            sb.append("<th style='").append(thStyle).append("'>学分</th>");
            sb.append("<th style='").append(thStyle).append("'>学时</th>");
            sb.append("<th style='").append(thStyle).append("'>学期</th>");
            sb.append("<th style='").append(thStyle).append("'>先修课程ID</th>");
            sb.append("</tr>");

            for (Course cou : courseList) {
                sb.append("<tr>")
                        .append("<td style='").append(tdStyle).append("'>").append(cou.getCouid()).append("</td>")
                        .append("<td style='").append(tdStyle).append("'>").append(cou.getCoursename()).append("</td>")
                        .append("<td style='").append(tdStyle).append("'>").append(cou.getCredits()).append("</td>")
                        .append("<td style='").append(tdStyle).append("'>").append(cou.getHours()).append("</td>")
                        .append("<td style='").append(tdStyle).append("'>").append(cou.getSemester()).append("</td>")
                        .append("<td style='").append(tdStyle).append("'>").append(cou.getCouPno() != 0 ? cou.getCouPno() : "无").append("</td>")
                        .append("</tr>");
            }
            sb.append("</table>");
        }
        return sb.toString();
    }

    private String generateStudentDetailHtml(Student student) {
        StringBuilder sb = new StringBuilder();
        if (student == null) {
            return "<p>学生信息不存在</p>";
        }
        String tableStyle = "border-collapse: collapse; width: 50%; font-family: Microsoft YaHei UI; margin-top: 10px;";
        String labelStyle = "border: 1px solid #ddd; padding: 8px; background-color: #f0f8ff; font-weight: bold; width: 30%;";
        String valueStyle = "border: 1px solid #ddd; padding: 8px;";
        sb.append("<table style='").append(tableStyle).append("'>");
        sb.append("<tr><td style='").append(labelStyle).append("'>学生ID</td><td style='").append(valueStyle).append("'>").append(student.getStuid()).append("</td></tr>");
        sb.append("<tr><td style='").append(labelStyle).append("'>姓名</td><td style='").append(valueStyle).append("'>").append(student.getStuName()).append("</td></tr>");
        sb.append("<tr><td style='").append(labelStyle).append("'>性别</td><td style='").append(valueStyle).append("'>").append(student.getStuGender()).append("</td></tr>");
        sb.append("<tr><td style='").append(labelStyle).append("'>入学年份</td><td style='").append(valueStyle).append("'>").append(student.getEnrolledYear()).append("</td></tr>");
        sb.append("<tr><td style='").append(labelStyle).append("'>联系电话</td><td style='").append(valueStyle).append("'>")
                .append(student.getStuPhone() != null ? student.getStuPhone() : "未填写")
                .append("</td></tr>");
        sb.append("<tr><td style='").append(labelStyle).append("'>专业</td><td style='").append(valueStyle).append("'>").append(student.getStuMajor()).append("</td></tr>");
        sb.append("</table>");
        return sb.toString();
    }

    private String generateCourseDetailHtml(Course course) {
        if (course == null) {
            return "<p>课程信息不存在</p>";
        }
        StringBuilder sb = new StringBuilder();
        String tableStyle = "border-collapse: collapse; width: 50%; font-family: Microsoft YaHei UI; margin-top: 10px;";
        String labelStyle = "border: 1px solid #ddd; padding: 8px; background-color: #f0f8ff; font-weight: bold; width: 30%;";
        String valueStyle = "border: 1px solid #ddd; padding: 8px;";
        sb.append("<table style='").append(tableStyle).append("'>");
        sb.append("<tr><td style='").append(labelStyle).append("'>课程ID</td><td style='").append(valueStyle).append("'>").append(course.getCouid()).append("</td></tr>");
        sb.append("<tr><td style='").append(labelStyle).append("'>课程名称</td><td style='").append(valueStyle).append("'>").append(course.getCoursename()).append("</td></tr>");
        sb.append("<tr><td style='").append(labelStyle).append("'>学分</td><td style='").append(valueStyle).append("'>").append(course.getCredits()).append("</td></tr>");
        sb.append("<tr><td style='").append(labelStyle).append("'>学时</td><td style='").append(valueStyle).append("'>").append(course.getHours()).append("</td></tr>");
        sb.append("<tr><td style='").append(labelStyle).append("'>开课学期</td><td style='").append(valueStyle).append("'>").append(course.getSemester()).append("</td></tr>");
        sb.append("<tr><td style='").append(labelStyle).append("'>先修课程ID</td><td style='").append(valueStyle).append("'>")
                .append(course.getCouPno() != 0 ? course.getCouPno() : "无")
                .append("</td></tr>");
        sb.append("</table>");
        return sb.toString();
    }

    private void displayResult(List<course_t> scList) {
        StringBuilder sb = new StringBuilder();
        sb.append("<html><body style='font-family:Microsoft YaHei UI; font-size:14px;'>");
        sb.append("<h3 style='color:").append(toHtmlColor(PRIMARY_BLUE)).append(";'>查询结果</h3>");

        if (scList.isEmpty()) {
            sb.append("<p>无匹配记录</p>");
        } else {
            String tableStyle = "width: 80%; border-collapse: collapse; font-family: Microsoft YaHei UI;";
            String thStyle = "border: 1px solid #ddd; padding: 10px; text-align: left; background-color: #f0f8ff; color: #333;";
            String tdStyle = "border: 1px solid #ddd; padding: 10px; text-align: left;";
            sb.append("<table style='").append(tableStyle).append("'>");
            sb.append("<tr>");
            sb.append("<th style='").append(thStyle).append("'>学生ID</th>");
            sb.append("<th style='").append(thStyle).append("'>姓名</th>");
            sb.append("<th style='").append(thStyle).append("'>课程ID</th>");
            sb.append("<th style='").append(thStyle).append("'>课程名称</th>");
            sb.append("<th style='").append(thStyle).append("'>成绩</th>");
            sb.append("</tr>");
            for (course_t sc : scList) {
                Student student = stuDao.getStudentById(sc.getStuid());
                String studentName = student != null ? student.getStuName() : "未知";
                Course course = couDao.getCoureseById(sc.getCouid());
                String courseName = course != null ? course.getCoursename() : "未知";
                sb.append("<tr>");
                sb.append("<td style='").append(tdStyle).append("'>").append(sc.getStuid()).append("</td>");
                sb.append("<td style='").append(tdStyle).append("'>").append(studentName).append("</td>");
                sb.append("<td style='").append(tdStyle).append("'>").append(sc.getCouid()).append("</td>");
                sb.append("<td style='").append(tdStyle).append("'>").append(courseName).append("</td>");
                sb.append("<td style='").append(tdStyle).append("'>").append(sc.getGrade()).append("</td>");
                sb.append("</tr>");
            }
            sb.append("</table>");
        }
        sb.append("</body></html>");
        resultArea.setContentType("text/html");
        resultArea.setText(sb.toString());
    }
}
